package com.cnpinxi.tool;


import com.cnpinxi.log.LogFactory;
import com.cnpinxi.myRunTime.MyRunTimeExcption;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;


/**
 * <p>
 * Description: Http客户端辅助类
 * </p>
 *
 * @author
 */
@SuppressWarnings("deprecation")
public class HttpClientHelper {
    public static Logger logger = LogFactory.getLogger(HttpClientHelper.class);
    public static Integer CONNECT_TIMEOUT = 18000;
    public static Integer READ_TIMEOUT = 18000;
    //请求器的配置
    private static RequestConfig requestConfig;
    public HttpClientHelper() {
        // TODO Auto-generated constructor stub
    }

    /**
     * 添加请求参数
     *
     *
     * @author
     */
    private static List<NameValuePair> addParameter(Map<String, String> map) {

        List<NameValuePair> paramList = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : map.entrySet()) {

            paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return paramList;
    }

    /**
     * post请求
     *
     * @param url
     *            请求地址
     * @return 请求结果内容
     * @throws Exception
     * @author
     */
    public static String doPost(String url, Map<String, String> map) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        setTimeoutParameters(httpclient);
        String result = "";
        HttpEntity entity = null;
        // 创建httppost
        HttpPost httppost = new HttpPost(url);

        try {
            // 编码实体
            UrlEncodedFormEntity urlEncodeEntyty;
            // 编码
            urlEncodeEntyty = new UrlEncodedFormEntity(addParameter(map), "utf-8");
            // 绑定到post对象
            httppost.setEntity(urlEncodeEntyty);
            // 执行httppost
            HttpResponse response = httpclient.execute(httppost);
            // 获取相应实体
            entity = response.getEntity();

            if (null != entity && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(entity);
            }
        } catch (Exception e) {

            throw e;
        } finally {
            if (null != entity) {
                EntityUtils.consume(entity);
            }
            if (null != httppost) {
                httppost.abort();
            }
            if (null != httpclient) {
                httpclient.getConnectionManager().shutdown();
            }
        }

        return result;
    }

    /**
     * get请求
     *
     * @param url
     *            请求地址
     * @return 请求结果内容
     * @throws Exception
     * @author
     */
    public static String doGet(String url) throws Exception {
        String result = "";
        HttpEntity entity = null;
        HttpClient httpclient = new DefaultHttpClient();
        setTimeoutParameters(httpclient);
        // 创建HttpGet
        HttpGet httpget = new HttpGet(url);
        try {
            // 执行get请求
            HttpResponse response = httpclient.execute(httpget);
            // 获取相应实体
            entity = response.getEntity();
            System.out.println("  response.getStatusLine().getStatusCode():::"+  response.getStatusLine().getStatusCode());

            if (null != entity && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
e.printStackTrace();
            throw e;
        } finally {
            if (null != entity) {
                EntityUtils.consume(entity);
            }
            if (null != httpget) {
                httpget.abort();
            }
            if (null != httpclient) {
                httpclient.getConnectionManager().shutdown();
            }
        }
System.out.println(result);
        return result;
    }

    /**
     * 获取URL网络状态
     *
     * @param url
     *            服务器地址
     * @return 正常访问返回true、异常返回false
     * @author
     */
    public static boolean getUrlState(String url) {
        HttpClient httpclient = new DefaultHttpClient();
        setTimeoutParameters(httpclient);
        // 创建HttpGet
        HttpGet httpget = new HttpGet(url);
        try {
            // 执行get请求
            HttpResponse response = httpclient.execute(httpget);
            // 获取相应实体
            int state = response.getStatusLine().getStatusCode();

            return state == HttpStatus.SC_OK;
        } catch (Exception e) {

            return false;
        } finally {
            if (null != httpget) {
                httpget.abort();
            }
            if (null != httpclient) {
                httpclient.getConnectionManager().shutdown();
            }
        }
    }

    public static String doPost2(String url, Map<String, String> map) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        setTimeoutParameters(httpclient);
        String result = "";
        HttpEntity entity = null;
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        try {
            // 编码实体
            UrlEncodedFormEntity urlEncodeEntyty;
            // 编码
            urlEncodeEntyty = new UrlEncodedFormEntity(addParameter(map), "utf-8");
            // 绑定到post对象
            httppost.setEntity(urlEncodeEntyty);
            // 执行httppost
            HttpResponse response = httpclient.execute(httppost);
            // 获取相应实体
            entity = response.getEntity();

            if (null != entity && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                Header[] hs = response.getHeaders("Content-Encoding");
                boolean flag = false;
                if (hs.length > 0) {
                    String a = "gzip";
                    if (Arrays.toString(hs).indexOf(a) > 0) {
                        flag = true;
                    }
                }
                if (flag) {
                    byte[] bResult = EntityUtils.toByteArray(entity);
                    GZIPInputStream gzin = new GZIPInputStream(new ByteArrayInputStream(bResult));
                    InputStreamReader isr = new InputStreamReader(gzin, "utf-8");
                    BufferedReader br = new BufferedReader(isr);
                    StringBuffer sb = new StringBuffer();
                    String tempbf;
                    while ((tempbf = br.readLine()) != null) {
                        sb.append(tempbf);
                        sb.append("\r\n");
                    }
                    isr.close();
                    gzin.close();
                    result = sb.toString();
                } else {
                    result = EntityUtils.toString(entity);
                }
            }
        } catch (Exception e) {

            throw e;
        } finally {
            if (null != entity) {
                EntityUtils.consume(entity);
            }
            if (null != httppost) {
                httppost.abort();
            }
            if (null != httpclient) {
                httpclient.getConnectionManager().shutdown();
            }
        }

        return result;
    }


    /**
     * 只发送字符串
     * @param url
     * @param requestString
     * @return
     */
    public static String stringPost(String url, String requestString) {
        HttpClient httpclient = new DefaultHttpClient();
        setTimeoutParameters(httpclient);

        HttpResponse response = null;
        HttpEntity httpEntity = null;
        HttpPost httpPost = null;
        try {
            httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "text/xml");
            if (requestString != null && requestString.length() > 0) {
                httpPost.setEntity(new StringEntity(requestString,"UTF-8" ));
            }
            //设置请求器的配置
            httpPost.setConfig(requestConfig);
            response = httpclient.execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                logger.warn("【请求失败。。。。。。】");
                return null;
            }
            httpEntity = response.getEntity();
            InputStream inputStream = httpEntity.getContent();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            StringBuffer stringBuffer = new StringBuffer();
            String dataTeam;
            while((dataTeam = bufferedReader.readLine()) != null) {
                stringBuffer.append(dataTeam);
            }

            String result = stringBuffer.toString();
            System.out.println(result);
            bufferedReader.close();
            inputStream.close();
            /*if (httpEntity != null) {
                result = EntityUtils.toString(httpEntity, "utf-8");
            }*/

            return result;
        } catch (IOException e) {
            System.out.println("接口请求出错："+ e.getMessage());
            throw new MyRunTimeExcption("【接口请求出错】。。。。。。");
        } catch (Exception e) {
            System.out.println("接口请求出错："+ e.getMessage());
            throw new MyRunTimeExcption("【接口请求出错】。。。。。。");
        } finally {// 释放资源
            try {
                if (null != httpEntity) {
                    EntityUtils.consume(httpEntity);
                }
                if (null != httpPost) {
                    httpPost.abort();
                }
                if (null != httpclient) {
                    httpclient.getConnectionManager().shutdown();
                }
            } catch (Exception e) {
                System.out.println("【远程请求资源关闭出错：" + e.getMessage()+"】。。。。。。");
            }
        }
    }

    private static HttpClient setTimeoutParameters(HttpClient httpclient) {
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECT_TIMEOUT);
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, READ_TIMEOUT);
        return httpclient;
    }

    public static void main(String[] str) throws Exception {
        PropertyConfigurator.configure("E://baggio//EducationWebSite//src//main//resources//conf//log4j.properties");
        // String dd= doGet("http://localhost:8080/getShoppingCartList?customerId=17");
       //  String dd= doGet("http://localhost:8080/createOrder?classIds=1&customerId=17&productType=2&isShoppingCart=false");
    //  String dd= doGet("http://localhost:8080/cancelOrderItem?orderItemId=14831209818100005&customerId=17&productType=1");
       /* Map<String,String> map=new HashMap<String,String>();
        map.put("orderItemIds","14833079065830002");
        map.put("classId","29");*/
     //   map.put("replyId","1484556693940002_29_19_1");
     //  String dd= doPost("http://127.0.0.1:8080/getBuyerReplyList",map);
        //String dd= doPost("http://newpayment-test.chinapay.com/CTITS/service/rest/page/nref/000000000017/0/0/0/0/0",map);
  /*      PayParameter payParameter = new PayParameter();
        Map<String, String> parameterMap = new HashMap<String, String>();

        parameterMap.put("appid", FixedData.ENTERPRISE_APP_ID);
        parameterMap.put("mch_id", FixedData.MERCHANT_NUMBER);
        parameterMap.put("nonce_str","sxnzgt1ce805k7uqmp3wi2d9a4lohfbv");
        parameterMap.put("body", "JAZZ 舞");
        //parameterMap.put("body", "xinyi");
        parameterMap.put("out_trade_no", "1488216860491001");
        parameterMap.put("total_fee", "100");
        parameterMap.put("spbill_create_ip", "127.0.0.1");
        parameterMap.put("notify_url", FixedData.ASYNCHRONOUS_RECEPTION);         // 微信异步反馈下订单结果信息的地址
        parameterMap.put("trade_type", "NATIVE");   // 为此值时才有二维码地址返回
        String sign_tmp = WeChatNotification.dictionarySorting(parameterMap) + "&key=" + FixedData.WX_KEY;
        String sign = MD5Tools.MD5(sign_tmp);//正确的写法).toUpperCase();
        logger.warn("【组装后的参数排序字符串：" + sign_tmp + "】。。。。。。");
        logger.warn("【最后生成的加密字段sign：" + sign + "】。。。。。。");
        parameterMap.put("sign", sign);

        String requestString = XmlAnalysisTools.stringToWxForXML(parameterMap);*/




//stringPost(FixedData.CREATE_ORDER_URL,requestString);

       // System.out.println("====>>>>"+dd);
    }
}
